package org.dev.hi.hiui.banner.core

import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.annotation.DrawableRes
import org.dev.hi.hiui.R
import org.dev.hi.library.util.HiDisPlayUtils

/**
 * Author WenPing
 * CreateTime 2021/4/17.
 * Description:创建圆形指示器
 */
class HiCircleIndicator @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyle: Int = 0
) : FrameLayout(context, attrs, defStyle), HiIndicator<FrameLayout?> {

    companion object {
        private const val VWC = ViewGroup.LayoutParams.WRAP_CONTENT
    }

    @DrawableRes
    private val mPointNormal = R.drawable.shape_point_normal

    @DrawableRes
    private val mPointSelected = R.drawable.shape_point_select


    /**
     * 指示器左右的内边距
     */
    private var mPointLeftRightPadding = 0

    /**
     * 指示器上下内间距
     */
    private var mPointTopBottomPadding = 0

    init {
        mPointLeftRightPadding = HiDisPlayUtils.dp2px(5f)
        mPointTopBottomPadding = HiDisPlayUtils.dp2px(15f)
    }

    override fun get(): FrameLayout = this

    /**
     * 根据对应的count数，在一个线性布局里添加具体的 指示器元素
     */
    override fun onInflate(count: Int) {
        removeAllViews()
        if (count <= 0) {
            return
        }
        val groupView = LinearLayout(context)
        groupView.orientation = LinearLayout.HORIZONTAL
        var imageView: ImageView
        val imageViewParams = LinearLayout.LayoutParams(VWC, VWC)
        imageViewParams.run {
            gravity = Gravity.CENTER_VERTICAL
            setMargins(
                mPointLeftRightPadding,
                mPointTopBottomPadding,
                mPointLeftRightPadding,
                mPointTopBottomPadding
            )
        }
        for (i in 0 until count) {
            imageView = ImageView(context)
            imageView.layoutParams = imageViewParams
            if (i == 0) {
                imageView.setImageResource(mPointSelected)
            } else {
                imageView.setImageResource(mPointNormal)
            }
            groupView.addView(imageView)
        }
        //使用framelayout的尺寸参数
        val groupViewParams = LayoutParams(VWC, VWC)
        groupViewParams.gravity = Gravity.CENTER or Gravity.BOTTOM
        addView(groupView,groupViewParams)
    }

    override fun onPointChange(current: Int, count: Int) {
        //获得线性聚
        val viewGroup = getChildAt(0) as ViewGroup
        for (i in 0 until viewGroup.childCount) {
           val imageView = viewGroup.getChildAt(i) as ImageView
            if (i == current) {
                imageView.setImageResource(mPointSelected)
            } else {
                imageView.setImageResource(mPointNormal)
            }
            //在for循环里进行重新设置 指示器元素的显示，并且调用重绘方法实现重绘
            imageView.requestLayout()
        }
    }


}